import { Component, OnInit, ViewChild, Injector, ElementRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router'; //需要引入的库类
import { ServiceProxy, WarehouseDTO, SiteDTO, PathDTO, DispatchDTO } from '@shared/service-proxy/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { loadModules } from 'esri-loader';
import esri = __esri;
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
import { AppConsts } from "@shared/AppConsts";
@Component({
  selector: 'app-create-container-path',
  templateUrl: './create-container-path.component.html',
  styleUrls: ['./create-container-path.component.less']
})
export class CreateContainerPathComponent extends AppComponentBase implements OnInit {

  @ViewChild('mapViewNode') private mapViewEl: ElementRef;

  companyList: WarehouseDTO[] = [];
  startCompanyList: WarehouseDTO[] = [];
  endCompanyList: WarehouseDTO[] = [];
  sites: SiteDTO[] = [];
  validateForm: FormGroup;
  pathList: PathDTO[] = [];
  tempPathList: PathDTO[] = [];
  selectedPath: string = '';
  pathModel: PathDTO = new PathDTO();
  model: DispatchDTO = new DispatchDTO();
  legendShow: boolean = true;
  params: string;
  routeParams: any;
  disList: DispatchDTO[];
  currentSiteId:string;
  siteId:string;

  constructor(injector: Injector,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private _service: ServiceProxy) {
    super(injector);
  }

  ngOnInit() {
    this.routeParams = {
      launchsiteId: '', destinationsiteId: '', containerCode: '', containerStatus: [3]
    };
    this.validateForm = this.fb.group({
      launchsiteId: [null, [Validators.required]],
      destinationsiteId: [null, [Validators.required]],
      startWarehouseId: [null, [Validators.nullValidator]],
      endWarehouseId: [null, [Validators.nullValidator]],
      routeId: [null, [Validators.nullValidator]],
      timeLimit: [null, [Validators.required]],
    });
    this.currentSiteId = this.appSession.user.siteId;
 
    this.getAllSites();
    this.getAllCompany();
    this.model = new DispatchDTO();
    if (this.currentSiteId) {
      this.siteId = this.currentSiteId;
      this.model.launchsiteId=this.siteId;
    }
    
    //this.pathModel = new PathDTO();
    this.model.containerId = this.route.params["value"].id;
    this.model.containerCode = this.route.params["value"].containerNo;
    this.initializeMap();
  }

  getAllSites() {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    });
  }

  getAllCompany() {
    this._service.getAllWarehouseDTOsUsingGET().subscribe(result => {
      this.companyList = result.result.fieldList;

      if(this.currentSiteId){
        this.getCompanyForStart()
      }
    });
  }

  getCompanyForStart() {
    this.pathModel.startWarehouseId = null;
    this.startCompanyList = this.companyList.filter(m => m.siteId == this.model.launchsiteId);
    this.getPathList();
  }

  getCompanyForEnd() {
    this.pathModel.endWarehouseId = null;
    this.endCompanyList = this.companyList.filter(m => m.siteId == this.model.destinationsiteId);
    this.model.routeId = undefined;
    this.getPathList();
  }

  getDispatchList() {

    this._service.searchRouterAvgTimeUsingGET(this.model.routeId
    ).pipe(finalize(() => {
      // this.tableHelper.loading = false;
    })).subscribe((result) => {
      debugger
      this.disList = result.result.fieldList;
      if (this.disList.length) {
        var totalMin = 0;
        this.disList.forEach(element => {
          const timespan = moment(element.arriveTime).diff(moment(element.launchTime), 'seconds');
          totalMin += timespan / 3600;
        });
        this.model.timeLimit = (totalMin / this.disList.length).toString();
      }
    });
  }

  ceratePath() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.validateForm.valid) { // 验证通过

      this._service.startDispatchUsingPOST(this.model, this.model.containerId).subscribe(result => {
        if (result.success) {
          this.message.success(this.l('save_success'));
          this.router.navigate(['/basic/containers']);
        }
        else {
          this.message.info(this.l(result.error.message));
        }

      }, error => {
        this.message.error(this.l(error.message));
      });
    }
  }

  return() {
    this.router.navigate(['/basic/containers']);
  }

  getPathList() {
    debugger;
    if (this.model.launchsiteId &&
      this.model.destinationsiteId) {

      this._service.getAllPathUsingGET().subscribe(result => {
        this.tempPathList = result.result.fieldList;

        if (this.pathModel.startWarehouseId && this.pathModel.endWarehouseId) {
          this.pathList = this.tempPathList.filter(m => m.startSiteId == this.model.launchsiteId
            && m.endSiteId == this.model.destinationsiteId
            && m.startWarehouseId == this.pathModel.startWarehouseId
            && m.endWarehouseId == this.pathModel.endWarehouseId
            && m.startWarehouseId == this.pathModel.startWarehouseId);
        }
        else if (this.pathModel.startWarehouseId) {
          this.pathList = this.tempPathList.filter(m => m.startSiteId == this.model.launchsiteId
            && m.endSiteId == this.model.destinationsiteId
            && m.startWarehouseId == this.pathModel.startWarehouseId
            && (m.endWarehouseId == undefined || m.endWarehouseId == "" || m.endWarehouseId == null));
        }
        else if (this.pathModel.endWarehouseId) {
          this.pathList = this.tempPathList.filter(m => m.startSiteId == this.model.launchsiteId
            && m.endSiteId == this.model.destinationsiteId
            && m.endWarehouseId == this.pathModel.endWarehouseId
            && (m.startWarehouseId == undefined || m.startWarehouseId == "" || m.startWarehouseId == null));
        }
        else {
          this.pathList = this.tempPathList.filter(m => m.startSiteId == this.model.launchsiteId
            && m.endSiteId == this.model.destinationsiteId
            && (m.endWarehouseId == undefined || m.endWarehouseId == "" || m.endWarehouseId == null)
            && (m.startWarehouseId == undefined || m.startWarehouseId == "" || m.startWarehouseId == null));
        }

      });

      this.getDispatchList();
    }

  }

  getPath() {
    const path = this.pathList.find(m => m.id == this.model.routeId);
    if (path) {
      this.selectedPath = path.geoJson;
      const currentSite = this.sites.find(m => m.id == this.model.launchsiteId);
      if (currentSite) {
        this._center = [currentSite.lng, currentSite.lat];
      }
      this.initializeMap();
    }
  }

  async initializeMap() {
    try {
      const [
        Map,
        MapView,
        ScaleBar,
        TileLayer,
        Graphic,
        GraphicsLayer] = await loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/widgets/ScaleBar',
          'esri/layers/TileLayer',
          "esri/Graphic",
          "esri/layers/GraphicsLayer",
          'dojo/domReady!'
        ], {
            url: AppConsts.arcgisMapUrl,         css: AppConsts.arcgisStyleUrl
          });

      const tempGraphicsLayer = new GraphicsLayer();
      var layer = new TileLayer({
        url: AppConsts.arcgisMapServerUrl
      });

      // Set type of map
      const map: esri.Map = new Map({
        // basemap: this._basemap,
        layers: [layer, tempGraphicsLayer]
      });

      const mapView: esri.MapView = new MapView({
        container: this.mapViewEl.nativeElement,
        center: this._center,
        zoom: this._zoom,
        map: map
      });

      // All resources in the MapView and the map have loaded.
      // Now execute additional processes
      mapView.when(() => {
        const scaleBar = new ScaleBar({
          view: mapView,
          unit: "dual" // The scale bar displays both metric and non-metric units.
        });
        mapView.ui.add(scaleBar, "bottom-left");

        if (this.selectedPath) {
          selectPath(this);
        }

        function selectPath(_that) {
          const transJson = Graphic.fromJSON(JSON.parse(_that.selectedPath));
          tempGraphicsLayer.add(transJson);
          _that.model.geoJson = _that.selectedPath;
        }
      });
    } catch (error) {
      console.log('We have an error: ' + error);
    }

  }

}
